<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Citizen extends CI_Model
{
	protected $table = 'citizen';
	protected $citytable = 'incity';
	
	public function loadCitizen( $id )
	{	
		return $this->db->select('*')
						->from( $this->table )
						->where( 'id', $id )
						->get()
						->result();
	}
	
	public function addCitizen( $citizen, $city_id = 0 )
	{
		$res = $this->db->select( 'id' )
						->from( $this->table )
						->where( 'id', $citizen['id'] )
						->get()
						->result();
						
		
		$this->db->set( 'nickname', $citizen['nickname'] );
		if( isset( $citizen['avatar'] ) )
			$this->db->set( 'avatar', $citizen['avatar'] );
			
		if( empty( $res ) )
		{ // add to db
			$this->db->set( 'id', $citizen['id'] );
			$this->db->insert( $this->table );
		}
		else
		{ // update db
			$this->db->where( 'id',  $citizen['id'] );
			$this->db->update( $this->table );
		}
		
		if( $city_id != 0 )
		{
			$res = $this->db->select( 'id_citizen, id_city' )
						->from( $this->citytable )
						->where( 'id_citizen', $citizen['id'] )
						->where( 'id_city', $city_id )
						->get()
						->result();
			
			if( empty( $res ) )
			{ // add to db
				$this->db->set( 'id_citizen', $citizen['id'] )
						->set( 'id_city', $city_id );
				$this->db->insert( $this->citytable );
			}
		}
		
		return $citizen;
	}
}


/* End of file citizen.php */
/* Location: ./application/models/citizen.php */